//
//  ShopMallDetailVC.m
//  YBLive
//
//  Created by ybRRR on 2020/8/20.
//  Copyright © 2020 cat. All rights reserved.
//

#import "ShopMallDetailVC.h"
#import "SPPageMenu.h"
#import "ShopCell.h"
#import "OutsideGoodsDetailVC.h"
#import "CommodityDetailVC.h"

@interface ShopMallDetailVC ()<SPPageMenuDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
{
    UIView *selBtnView;
    UIButton *newBtn;
    UIButton *sellBtn;
    UIButton *priceBtn;
    
    BOOL sellIsUp;
    BOOL priceIsUp;

    NSString *_classId;
    NSString *sellSortStr;
    NSString *priceSortStr;
    NSString *isnew;
    
    int pageIndex;
}
@property (nonatomic, weak) SPPageMenu *pageMenu;
@property (nonatomic, strong)NSMutableArray *titleArr;
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *infoArray;
@property(nonatomic,strong)NSArray *classArray;

@end

@implementation ShopMallDetailVC
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0,*)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}

#pragma mark--------网络请求------------
-(void)requestListData{
    
    [WYNetworking postWithUrl:@"Home.getShopClassList" Dic:@{@"shopclassid":_classId,@"sell":sellSortStr,@"price":priceSortStr,@"isnew":isnew,@"p":@(pageIndex)} Suc:^(int code, id info, NSString *msg) {
        [_collectionView.mj_header endRefreshing];
        [_collectionView.mj_footer endRefreshing];
        if (code == 0) {
            NSArray *list =info;
            if (pageIndex == 1) {
                [_infoArray removeAllObjects];
            }
            [_infoArray addObjectsFromArray:list];
            [_collectionView reloadData];
            if (_infoArray.count < 1) {
                [PublicView showTextNoData:_collectionView text1:YZMsg(@"暂无商品") text2:@""centerY:0.6];
            }else{
                [PublicView hiddenTextNoData:_collectionView];
            }
        if (list.count == 0) {
            [_collectionView.mj_footer endRefreshingWithNoMoreData];
        }
    }

    } Fail:^(id fail) {
        [_collectionView.mj_header endRefreshing];
        [_collectionView.mj_footer endRefreshing];

    }];
}

-(void)inintData{
    _titleArr = [NSMutableArray array];
    self.infoArray = [NSMutableArray array];
    pageIndex = 1;
    sellSortStr = @"";
    priceSortStr = @"";
    isnew = @"0";
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleL.text = minstr([self.classDic valueForKey:@"gc_name"]);
    self.view.backgroundColor = RGB(250, 250, 250);
    self.subNavi.backgroundColor = UIColor.whiteColor;
    self.titleL.textColor = UIColor.blackColor;
    [self.leftBtn setImage:[UIImage imageNamed:@"pub_back_black"] forState:0];
    self.naviLine.hidden = NO;
    self.naviLine.backgroundColor = RGB(245, 245, 245);

    [self inintData];
    
    [self setHeadClass];
    [self getThreeClass];

    [self setSelClassBtn];
    [self createCollectionView];
    
}
#pragma mark----------获取三级分类-----------begin----
-(void)setHeadClass{
    SPPageMenu *pageMenu = [SPPageMenu pageMenuWithFrame:CGRectMake(0, 64+statusbarHeight, _window_width, 40) trackerStyle:SPPageMenuTrackerStyleLine];
    pageMenu.delegate = self;
    pageMenu.dividingLine.hidden = YES;
    pageMenu.tracker.backgroundColor = Pink_Cor;
    pageMenu.selectedItemTitleColor = Pink_Cor;
    pageMenu.unSelectedItemTitleColor = [UIColor blackColor];
    pageMenu.selectedItemTitleFont =  [UIFont systemFontOfSize:14];
    pageMenu.unSelectedItemTitleFont = [UIFont systemFontOfSize:14];
    [self.view addSubview:pageMenu];
    _pageMenu = pageMenu;

}
-(void)getThreeClass{
    YBWeakSelf;
    
    NSString *url = [purl stringByAppendingFormat:@"?service=Home.getShopThreeClass"];
    NSDictionary *dic = @{
        @"shopclassid":minstr([self.classDic valueForKey:@"gc_id"])
                          };

    [WYNetworking postWithUrl:@"Home.getShopThreeClass" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            NSArray *infos =info;
            _classArray = infos;
            for ( NSDictionary *dic in infos) {
                [self.titleArr addObject:minstr([dic valueForKey:@"gc_name"])];
            }
            [_pageMenu setItems:self.titleArr selectedItemIndex:0];
            _classId = minstr([infos[0]valueForKey:@"gc_id"]);

            [weakSelf requestListData];

        }

        } Fail:^(id fail) {
            
        }];
    
}
- (void)pageMenu:(SPPageMenu *)pageMenu itemSelectedAtIndex:(NSInteger)index {
    NSLog(@"sssssss::::%zd",index);
    _classId = minstr([_classArray[index]valueForKey:@"gc_id"]);
    pageIndex =1 ;
    [self requestListData];

}
#pragma mark----------获取三级分类-----------end----

-(void)setSelClassBtn{
    
    selBtnView = [[UIView alloc]initWithFrame:CGRectMake(0, _pageMenu.bottom, _window_width, 40)];
    [self.view addSubview:selBtnView];
    
    newBtn = [UIButton buttonWithType:0];
    newBtn.frame = CGRectMake(12, 10, 60, 20);
    [newBtn setTitle:YZMsg(@"新品") forState:UIControlStateNormal];
    [newBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [newBtn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    newBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [newBtn addTarget:self action:@selector(newBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [selBtnView addSubview:newBtn];
    
    sellBtn = [UIButton buttonWithType:0];
    sellBtn.frame = CGRectMake(newBtn.right+12, 10, 60, 20);
    [sellBtn setTitle:YZMsg(@"销量") forState:UIControlStateNormal];
    [sellBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [sellBtn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    sellBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [sellBtn setImage:[UIImage imageNamed:@"sel_up"] forState:UIControlStateSelected];
    [sellBtn setImage:[UIImage imageNamed:@"sel_normal"] forState:UIControlStateNormal];
    sellBtn.titleEdgeInsets = UIEdgeInsetsMake(0,-sellBtn.imageView.frame.size.width, 0, sellBtn.imageView.frame.size.width);
    sellBtn.imageEdgeInsets = UIEdgeInsetsMake(0,sellBtn.titleLabel.bounds.size.width, 0, - sellBtn.titleLabel.bounds.size.width);
    [sellBtn addTarget:self action:@selector(sellBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [selBtnView addSubview:sellBtn];
    
    priceBtn = [UIButton buttonWithType:0];
    priceBtn.frame = CGRectMake(sellBtn.right+12, 10, 60, 20);
    [priceBtn setTitle:YZMsg(@"价格") forState:UIControlStateNormal];
    [priceBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [priceBtn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    priceBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [priceBtn setImage:[UIImage imageNamed:@"sel_up"] forState:UIControlStateSelected];
    [priceBtn setImage:[UIImage imageNamed:@"sel_normal"] forState:UIControlStateNormal];
    priceBtn.titleEdgeInsets = UIEdgeInsetsMake(0,-priceBtn.imageView.frame.size.width, 0, priceBtn.imageView.frame.size.width);
    priceBtn.imageEdgeInsets = UIEdgeInsetsMake(0,priceBtn.titleLabel.bounds.size.width, 0, - priceBtn.titleLabel.bounds.size.width);
    [priceBtn addTarget:self action:@selector(priceBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [selBtnView addSubview:priceBtn];

}
-(void)newBtnClick{
    sellIsUp = NO;
    priceIsUp = NO;
    newBtn.selected = YES;
    sellBtn.selected = NO;
    priceBtn.selected =NO;
    
    pageIndex = 1;
    isnew = @"1";
    sellSortStr = @"";
    priceSortStr = @"";
    [self requestListData];
}
-(void)sellBtnClick{
    sellBtn.selected = YES;
    priceBtn.selected =NO;
    newBtn.selected = NO;
    priceIsUp = NO;
    pageIndex = 1;

    sellIsUp = !sellIsUp;
    if (sellIsUp) {
        [sellBtn setImage:[UIImage imageNamed:@"sel_up"] forState:UIControlStateSelected];
        sellSortStr = @"asc";

    }else{
        [sellBtn setImage:[UIImage imageNamed:@"sel_down"] forState:UIControlStateSelected];
        sellSortStr = @"desc";

    }
    isnew = @"0";
    priceSortStr = @"";
    [self requestListData];

}
-(void)priceBtnClick{
    sellBtn.selected = NO;
    priceBtn.selected =YES;
    newBtn.selected = NO;
    sellIsUp = NO;
    pageIndex = 1;

    priceIsUp = !priceIsUp;
    if (priceIsUp) {
        [priceBtn setImage:[UIImage imageNamed:@"sel_up"] forState:UIControlStateSelected];
        priceSortStr = @"asc";

    }else{
        [priceBtn setImage:[UIImage imageNamed:@"sel_down"] forState:UIControlStateSelected];
        priceSortStr = @"desc";
    }
    isnew = @"0";
    sellSortStr = @"";
    [self requestListData];

}

-(void)createCollectionView{
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        flow.itemSize = CGSizeMake((_window_width-21)/2, (_window_width-21)/2 + 75);
        flow.minimumLineSpacing = 7;
        flow.minimumInteritemSpacing = 7;
        flow.sectionInset = UIEdgeInsetsMake(7, 7, 7, 7);

        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,selBtnView.bottom, _window_width, _window_height-64-statusbarHeight-_pageMenu.height-selBtnView.height) collectionViewLayout:flow];
        _collectionView.backgroundColor = RGB_COLOR(@"#f5f5f5", 1);
        _collectionView.delegate   = self;
        _collectionView.dataSource = self;
        [_collectionView registerNib:[UINib nibWithNibName:@"shopCell" bundle:nil] forCellWithReuseIdentifier:@"shopCELL"];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"hotHeaderV"];

        [self.view addSubview:_collectionView];

        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        
        _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            pageIndex = 1;
            [self requestListData];
        }];
        _collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            pageIndex ++;
            [self requestListData];
        }];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _infoArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
        ShopCell *cell = (ShopCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"shopCELL" forIndexPath:indexPath];
        NSDictionary *subDic = _infoArray[indexPath.row];
        [cell.thumbImgV sd_setImageWithURL:[NSURL URLWithString:minstr([subDic valueForKey:@"thumb"])]];
        cell.titleL.text = minstr([subDic valueForKey:@"name"]);
        cell.priceL.text = [NSString stringWithFormat:@"¥%@",minstr([subDic valueForKey:@"price"])];
        //type  商品类型   0 站内商品  1 外链商品
        if ([minstr([subDic valueForKey:@"type"]) isEqual:@"1"]) {
            cell.lineLb.hidden = NO;
            cell.sellCountLb.text = [NSString stringWithFormat:@"¥%@",minstr([subDic valueForKey:@"original_price"])];
        }else{
            cell.lineLb.hidden = YES;
            cell.sellCountLb.text =[NSString stringWithFormat:@"%@%@%@",YZMsg(@"已售"),minstr([subDic valueForKey:@"sale_nums"]),YZMsg(@"件")];
        }
        
        return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];

    NSDictionary *subDic = _infoArray[indexPath.row];
    
    [PublicObj checkGoodsExistenceWithID:minstr([subDic valueForKey:@"id"]) Existence:^(int code, NSString *msg) {
        if (code == 0) {
            if ([minstr([subDic valueForKey:@"type"]) isEqual:@"1"]) {
                OutsideGoodsDetailVC *detail = [[OutsideGoodsDetailVC alloc]init];
                detail.goodsID = minstr([subDic valueForKey:@"id"]);
                detail.liveUid = @"0";
                [[YBBaseAppDelegate sharedAppDelegate] pushViewController:detail animated:YES];

            }else{
                CommodityDetailVC *detail = [[CommodityDetailVC alloc]init];
                detail.goodsID = minstr([subDic valueForKey:@"id"]);
                detail.liveUid = @"0";
                [[YBBaseAppDelegate sharedAppDelegate] pushViewController:detail animated:YES];

            }

        }else{
            [MBProgressHUD showError:msg];

        }

    }];
    
}

@end
